#!/usr/bin/python
# -*- coding: utf-8 -*-

import re

def Client(tgt, module, argv):

    import salt.client

    local = salt.client.LocalClient()
    if argv:
        result = local.cmd(tgt, module, [argv], tgt_type='list')
    else:
        result = local.cmd(tgt, module, tgt_type='list')
    return result




def Os(tgt):
    os_argvs = ['localhost', 'kernel', 'kernelrelease', 'cpu_model', 'num_cpus', 'productname', 'os', 'osrelease',
                'mem_total']

    os_module = 'grains.item'

    oss = {}
    for argv in os_argvs:
        result = Client(tgt, os_module, argv)
        oss[argv] = result

    os_info = {}

    for ip in tgt:
        try:
            os_list = {}

            for argv in os_argvs:
                data = oss[argv][ip][argv]
                os_list[argv] = data
            os_info[ip] = os_list
        except:
            pass
    return os_info



def Disk(tgt):

    argv = "fdisk -l | grep -E 'sda:|sdb:|sdc:|vda:|vdb:|vdc:' |awk -F ',' '{print $1}'"
    disk_module = 'cmd.run'

    result = Client(tgt, disk_module, argv)
    disk_dict={}

    for ip in tgt:
        try:
            disk_infos = []
            if re.search("Disk",result[ip]):
                disk_infos =  result[ip].split("\n")
            else:
                argv = None
                disk_module = 'disk.usage'
                ip_tgt = [ip]
                result = Client(ip_tgt, disk_module, argv)
                for i in result[ip].keys():
                    disk_size = result[ip][i]["1K-blocks"]
                    if disk_size:
                        disk = i.strip("\\")+str(disk_size/1024/1024) +" GB"
                        disk_infos.append(disk)
                    else:
                        pass
            disk_info = sorted(disk_infos)
            disk_dict[ip] = {"disk_info":disk_info}
        except:
            pass
    return disk_dict


def Mem(tgt):
    argv = None
    module = 'status.meminfo'
    result = Client(tgt, module, argv)

    mem_info = {}

    for ip in tgt:
        try:
            SwapTotal = result[ip]['SwapTotal']['value']
        except:
            SwapTotal = 0
        mem_info[ip] = {"SwapTotal": SwapTotal}

    return mem_info


def main(tgt):
    os_info = Os(tgt)
    disk_info = Disk(tgt)
    mem_info = Mem(tgt)
    data = {}
    for ip in tgt:
        try:
            sys_info = dict(os_info[ip].items() + disk_info[ip].items() + mem_info[ip].items())
            data[ip] = sys_info
        except:
            pass
    return data



if __name__ == '__main__':
    tgt = ['192.168.1.218']
    result = main(tgt)
    print (result)
